<template>
  <div class="upload-image-button">
    <Button v-if="cacheSelectBtnVisible" class="m-r-5px" size="small" @click="uploadImageRecordModalVisible = true">从本地缓存选择</Button>
    <Button class="m-r-5px" size="small" @click="openSelectMyResourceModal">从资源库选择</Button>
    <div class="m-b-5px"></div>
    <Upload class=""
            type="drag"
            :action="uploadAction"
            :headers="{Authorization: token}"
            :data="{pageId: pageId}"
            :accept="accept"
            :format="uploadFormat"
            :max-size="maxSize"
            name="file"
            :on-success="imageUploadSuccessHandle"
            :on-format-error="imageUploadFormatError"
            :on-exceeded-size="imageUploadExceededSize"
            :before-upload="imageUploadBeforeUpload"
            :on-error="imageUploadErrorHandle"
            :show-upload-list="false">
      <!--<Button size="small" icon="ios-cloud-upload-outline">上传图片</Button>-->
      <div style="padding: 10px 0">
        <div v-if="!relativePath">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>点击或拖拽文件到这里上传</p>
        </div>
        <div v-else>
          <img style="max-width: 100%; height: 80px;" :src="AXIOS_BASE_URL + relativePath"/>
        </div>
      </div>
      <Spin fix v-if="uploadLoading">
        <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        <div>上传中...</div>
      </Spin>
    </Upload>

    <Modal
        v-model="uploadImageRecordModalVisible"
        draggable
        scrollable
        title="本地图片缓存"
        width="1024"
        :mask="true"
        :z-index="999"
        @on-visible-change="visibleChangeHandle">
      <div class="upload-image-record">
        <div class="none-alert" v-if="images.length == 0">
          查找不到本地缓存图片数据
        </div>
        <div v-if="images.length > 0" style="margin-bottom: 10px;">
          <Button size="small" type="error" @click="clearUploadImageRecord"><Icon type="md-trash" /> 清空本地图片缓存</Button>
        </div>
        <Row :gutter="10">
          <i-col span="4" v-for="(image, index) in images" :key="index">
            <div class="img-card"
                 @click="imgCardClickHandle(image)">
              <img :src="imageSrc(image)" />
            </div>
            <div style="margin-bottom: 10px;"></div>
          </i-col>
        </Row>
      </div>
      <div slot="footer">
        <Button type="default" @click="uploadImageRecordModalVisible = false">关闭</Button>
      </div>
    </Modal>

    <SelectMyResourceModal ref="selectMyResourceModal" @affirmSelect="selectMyResourceAffirmSelectHandler"></SelectMyResourceModal>
  </div>
</template>

<script>
  export default {
    name: 'UploadImageButton',
    props: {
      value: {
        type: String
      },
      pageId: {
        type: String,
        default: ''
      },
      useCustomHandler: {
        type: Boolean
      },
      accept: {
        type: String,
        default: '.jpg,.jpeg,.png,.gif,.svg'
      },
      maxSize: {
        type: Number,
        default: 5120
      },
      cacheSelectBtnVisible: {  // 从本地缓存选择按钮的显示隐藏，默认显示
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        AXIOS_BASE_URL: window.g.AXIOS_BASE_URL,
        token: localStorage.getItem('token'),
        relativePath: this.value,
        uploadAction: window.g.AXIOS_BASE_URL + '/file/upload',
        uploadImageRecordModalVisible: false,
        uploadLoading: false,

        images: []
      }
    },
    mounted() {
      this.$EventBus.$on('pn_uploadImageRecordChange', () => {
        this.initImages()
      })
    },
    destroyed() {
      this.$EventBus.$off('pn_uploadImageRecordChange')
    },
    methods: {

      /**
       * 文件上传成功
       * @param res
       */
      imageUploadSuccessHandle (res) {
        this.uploadLoading = false;
        if(res.success) {
          if (this.useCustomHandler) {
            this.$emit('upload-success', res.payload.relativePath);
          }else {
            this.relativePath = res.payload.relativePath;
          }
          this.$PnUtil.addImageToLocalStorage(res.payload.relativePath)
        }else {
          this.$Message.error(res.message)
        }
      },

      /**
       * 上传文件格式错误
       */
      imageUploadFormatError () {
        this.uploadLoading = false;
        this.$Message.warning({
          duration: 5,
          content: '上传文件格式错误，只支持（.jpg, .jpeg, .png, .gif, .svg）格式的图片文件'
        })
      },

      /**
       * 上传文件大小超出限制
       */
      imageUploadExceededSize () {
        this.uploadLoading = false;
        this.$Message.warning({
          duration: 5,
          content: '上传文件大小超出限制，上传文件不能超过5MB'
        })
      },

      /**
       * 上传文件之前
       */
      imageUploadBeforeUpload () {
        this.uploadLoading = true
      },

      /**
       * 文件上传失败时
       * @param error
       * @param file
       * @param fileList
       */
      imageUploadErrorHandle (error, file, fileList) {
        this.uploadLoading = false;
      },

      initImages () {
        if (localStorage.getItem('uploadImageRecord')) {
          this.images = JSON.parse(localStorage.getItem('uploadImageRecord'));
          // 过滤掉路径中没有包含pageId的数据项
          for (let i = this.images.length - 1; i >= 0; i--) {
            if (this.images[i].relativePath.indexOf(this.pageId) == -1) {
              this.images.splice(i, 1);
            }
          }
        }
      },
      visibleChangeHandle (val) {
        if (val == true) {
          this.initImages();
        }
      },
      clearUploadImageRecord () {
        this.$Modal.confirm({
          title: '提醒',
          content: '确认清空本地图片缓存吗？',
          onOk: () => {
            localStorage.setItem('uploadImageRecord', '[]');
            this.initImages()
          }
        });
      },
      imgCardClickHandle (image) {
        if (this.useCustomHandler) {
          this.$emit('record-ok', image.relativePath);
        }else {
          this.relativePath = image.relativePath;
        }
        this.uploadImageRecordModalVisible = false
      },
      imageSrc (image) {
        return window.g.AXIOS_BASE_URL + image.relativePath
      },

      openSelectMyResourceModal () {
        this.$refs.selectMyResourceModal.init()
      },

      selectMyResourceAffirmSelectHandler(resource) {
        this.$PnApi.ResourceApi.resourceTransferToPage(resource.id, this.pageId).then(result => {
          if (result.data.success) {
            if (this.useCustomHandler) {
              this.$emit('record-ok', result.data.payload);
            }else {
              this.relativePath = result.data.payload;
            }
          }else {
            this.$Message.error(result.data.message)
          }
        })
      }
    },
    computed: {
      uploadFormat() {
        let arr = this.accept.split(',')
        return arr.map((o)=>{return o.replace('.','')})
      }
    },
    watch: {
      value (val) {
        this.relativePath = val;
      },
      relativePath (val) {
        this.$emit('input', val);
      }
    }
  }
</script>

<style lang="less" scoped>
  .upload-image-button {
    margin-bottom: 5px;
  }
  .demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
  }
  .upload-image-record {
    height: 450px;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 10px;
    margin: -16px;
  }
  .img-card {
    width: 100%;
    height: auto;
    background-color: #fafafa;
    border: 2px solid #e0e0e0;
    border-radius: 4px;
    padding: 8px 8px 3px 8px;
    text-align: center;
    &.active {
      border-color: #039be5;
      box-shadow: 0 0 10px #000;
    }
    &:hover {
      box-shadow: 0 0 10px #000;
    }
    img {
      width: auto;
      height: 80px;
    }
  }
</style>
